package com.quanxi.qxaimain.service.hystrixServer;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.quanxi.qxaimain.common.globalException.ResultCode;

import com.quanxi.qxaimain.dao.indicators.indicatorsDataMapper;
import com.quanxi.qxaimain.service.demoserver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.List;

import static java.lang.Thread.sleep;


/**
 * @Author lyx
 * @create 2022/9/23 16:53
 */
@Slf4j
@Service("hystrixServer")

public class hystrixServerImpl implements hystrixServer {
    @Resource
   private indicatorsDataMapper indicatorsDataMapper;


    @Override
    @HystrixCommand(fallbackMethod = "fail",//执行降级方法
                                commandProperties = { @HystrixProperty(
                                   name = "execution.isolation.thread.timeoutInMilliseconds",
                                 value ="60000" )})

    public String demo(int timeMills) throws InterruptedException {
        sleep(timeMills);//延时xx毫秒
        System.out.println("成功");
        return "成功";
    }

    private String fail(int timeMills) {
        System.out.println("超时");
        return "超时";
    }


    @Resource
    demoserver demoserver;
    @Override
   @HystrixCommand(fallbackMethod = "overtimeSql60",//执行降级方法
                                                commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value ="60000" )})//60s 熔断机制
    public JSONObject exec_sql_overtime_60s(String sql)  {
        return exec_sql(sql);
    }

    private JSONObject overtimeSql60(String sql){//执行降级方法
        Long starttime = System.currentTimeMillis();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sql_message",ResultCode.SQL_OVER_TIME_60S);
        log.info(ResultCode.SQL_OVER_TIME_60S.getMsg());
        log.info(sql);
        jsonObject.put("sql_result","");
        jsonObject.put("sql",sql);
        jsonObject.put("time",System.currentTimeMillis()-starttime);
        //异步调用monDb
        //demoserver.springAsynchronousMethod();
        return jsonObject;
    }


  //超时继续等待执行
    public JSONObject exec_sql_overtime_no(String sql)  {
        JSONObject jsonObject = exec_sql(sql);

        //输出超时日志
        Enum<ResultCode> sql_message= (Enum<ResultCode>)jsonObject.get("sql_message");
        int code = ((ResultCode) sql_message).getCode();
        if (code==ResultCode.SQL_OVER_TIME_60S.getCode()){
            try {
                String root=  System.getProperty("user.dir")+"\\qxaimainlog\\SqlOvertime60s.txt";
                File fileOrFilename  = new File(root);
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOrFilename, true)));
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                out.write("================超时sql:"+df.format(System.currentTimeMillis())+"======="+"\r"+ sql+"\r");
                out.close();
                log.info("记录超时sql");
            }
            catch (Exception e ){
                log.info(e.getMessage());
            }
        }
        return jsonObject;
    }




    private JSONObject exec_sql(String sql)  {
        JSONObject jsonObject = new JSONObject();
        try{
            Long starttime = System.currentTimeMillis();
            List<LinkedHashMap<String, Object>> linkedHashMaps = indicatorsDataMapper.exec_sql(sql);
            jsonObject.put("sql_result", linkedHashMaps);
            jsonObject.put("sql_message", ResultCode.SQL_SUCCESS);
            jsonObject.put("sql",sql);
            if(System.currentTimeMillis()-starttime>Integer.valueOf(ResultCode.SQL_OVER_TIME.getMsg())){
                jsonObject.put("sql_message", ResultCode.SQL_OVER_TIME_60S);
            }
            jsonObject.put("time",System.currentTimeMillis()-starttime);
        }
        catch (Exception e){
            Long starttime = System.currentTimeMillis();
            jsonObject.put("sql_message",ResultCode.SQL_ERROR);
            jsonObject.put("sql_message_error",e.getMessage());
            log.info(e.getMessage());
            jsonObject.put("sql_result","");
            jsonObject.put("sql",sql);
            jsonObject.put("time",System.currentTimeMillis()-starttime);
        }
        return jsonObject;
    }



//超时执行 mongDb存储

    @Override
    @HystrixCommand(fallbackMethod = "fallbackMethod2",//执行降级方法
            commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value ="1000" )})//60s 熔断机制
    public JSONObject exec_sql_overtime_mondb(String sql) {
           return exec_sql(sql);
    }

    private JSONObject fallbackMethod2 (String sql){
        Long starttime = System.currentTimeMillis();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sql_message",ResultCode.SQL_OVER_TIME_60S);
        jsonObject.put("sql_result","");
        jsonObject.put("sql",sql);
        jsonObject.put("time",System.currentTimeMillis()-starttime);
        //异步调用monDb
         demoserver.sqlMongoDb(sql);
        return jsonObject;

    }



}